﻿namespace ApplicationFrame.EntityFrameworkCore.Core
{
    public class ShardingStrategyFactory
    {
        public IShardingStrategy<TEntity, TKey> Create<TEntity, TKey>() where TEntity : class
        {
            var entityType = typeof(TEntity);
            if (EntityFrameworkCoreExtensions.ShardingDic.TryGetValue(entityType, out var v))
            {
                // 1. 处理时间分表
                if (v.Item1 is TimeShardingAttribute timeAttr)
                    return (IShardingStrategy<TEntity, TKey>)(object)new TimeShardingStrategy<TEntity, TKey>(timeAttr.ShardingProperty, timeAttr.TimeGranularity);
                // 2. 处理哈希分表
                if (v.Item1 is HashShardingAttribute hashAttr)
                    return (IShardingStrategy<TEntity, TKey>)(object)new HashShardingStrategy<TEntity, TKey>(hashAttr.ShardingProperty, hashAttr.TableCount);
                // 3. 处理范围分表
                if (v.Item1 is RangeShardingAttribute rangeAttr)
                    return (IShardingStrategy<TEntity, TKey>)(object)new RangeShardingStrategy<TEntity, TKey>(rangeAttr.ShardingProperty, rangeAttr.RangeSize);
            }

            throw new InvalidOperationException($"实体{entityType.Name}未配置分表特性");
        }

        ///// <summary>
        ///// Create
        ///// </summary>
        ///// <typeparam name="TEntity">实体</typeparam>
        ///// <typeparam name="TKey1">时间分表字段</typeparam>
        ///// <typeparam name="TKey2">哈希分表字段</typeparam>
        ///// <returns></returns>
        ///// <exception cref="InvalidOperationException"></exception>
        //public IShardingStrategy<TEntity, Tuple<TKey1, TKey2>> Create<TEntity, TKey1, TKey2>() where TEntity : class, IShardingKey<Tuple<TKey1, TKey2>>
        //{
        //    var entityType = typeof(TEntity);

        //    // 1. 处理复合分表（时间+哈希）
        //    if (entityType.GetCustomAttribute<TimeHashShardingAttribute>() is { } timeHashAttr)
        //    {
        //        return (IShardingStrategy<TEntity, Tuple<TKey1, TKey2>>)(object)new TimeHashShardingStrategy<TEntity, TKey1, TKey2>(timeHashAttr.TimeGranularity, timeHashAttr.HashTableCount);
        //    }

        //    throw new InvalidOperationException($"实体{entityType.Name}未配置分表特性");
        //}
    }
}
